
-------


---生成模拟摇蛋数据

------------


string.split = function(s, p)
    local rt= {}
    string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
    return rt
end

function GetPath(path,cmd)
  local subPath= string.split(path, '\\')
  local subCmd= string.split(cmd, '/')
  local e = #subPath
  local s = 1
  for _,v in pairs(subCmd) do
  	if v==".." then
  		e=e-1
  		s=s+1
  	end
  end
  local  newPath = ""
  for i=1,e,1 do
  	newPath=newPath..subPath[i].."\\"
  end
  for j=s,#subCmd,1 do
  	newPath=newPath..subCmd[j].."\\"
  end
  return  newPath
end

function isNull(v)

	if v==nil or v=="" or v=="nil" then
		return true
	end
	return false
end

function fileExists(path)
  local file = io.open(path, "rb")
  if file then file:close() end
  return file ~= nil
end


function ToStringEx(value,tabcount)
    if type(value)=='table' then
        return TableToStr(value,tabcount)
    elseif type(value)=='string' then
        return "\'"..value.."\'"
    else
        return tostring(value)
    end
end

--使用的时候是这个
function TableToStr(t,tabcount)

	 tabcount = tabcount or 0
    if tabcount > 50 then
        --防止栈溢出
       -- return "<table too deep>"..tostring(t)
    end
    local tab =""-- string.rep("\t", tabcount)

    if t == nil then return "" end
    local retstr= "{"

    local i = 1
    for key,value in pairs(t) do
        local signal = ","
        if i==1 then
            signal = ""
        end

        if key == i then
            retstr = retstr..tab..signal..ToStringEx(value,tabcount+1)
        else
            if type(key)=='number' or type(key) == 'string' then
                retstr = retstr..signal..'['..ToStringEx(key,tabcount+1).."]="..ToStringEx(value,tabcount+1)
            else
                if type(key)=='userdata' then
                    retstr = retstr..tab..signal.."*s"..TableToStr(getmetatable(key),tabcount+1).."*e".."="..ToStringEx(value,tabcount+1)
                else
                    retstr = retstr..signal..key.."="..ToStringEx(value,tabcount+1)
                end
            end
        end

        i = i+1
    end

    retstr = retstr.."}"
    return retstr
end


function FormatValue(val)
    if type(val) == "string" then
        return string.format("%q", val)
    end
    return tostring(val)
end

function FormatTable(t, tabcount)
    tabcount = tabcount or 0
    if tabcount > 50 then
        --防止栈溢出
        return "<table too deep>"..tostring(t)
    end
    local str = ""
    if type(t) == "table" then
        for k, v in pairs(t) do
            local tab = string.rep("\t", tabcount)
            if type(v) == "table" then
                str = str..tab..string.format("[%s] = {", FormatValue(k))..'\n'
                str = str..FormatTable(v, tabcount + 1)..tab..'},\n'
            else
                str = str..tab..string.format("[%s] = %s", FormatValue(k), FormatValue(v))..',\n'
            end
        end
    else
        str = str..tostring(t)..'\n'
    end
    return str
end


function serialize(obj)
    local lua = ""
    local t = type(obj)
    if t == "number" then
        lua = lua .. obj
    elseif t == "boolean" then
        lua = lua .. tostring(obj)
    elseif t == "string" then
        lua = lua .. string.format("%q", obj)
    elseif t == "table" then
        lua = lua .. "{\n"
    for k, v in pairs(obj) do
        lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
    end
    local metatable = getmetatable(obj)
        if metatable ~= nil and type(metatable.__index) == "table" then
        for k, v in pairs(metatable.__index) do
            lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
        end
    end
        lua = lua .. "}"
    elseif t == "nil" then
        return nil
    else
        error("can not serialize a " .. t .. " type.")
    end
    return lua
end
function MyLuaToStr(t)
	local str=serialize(t)
	--local str = FormatTable(t)
	str="local data = "..str.." \n return data"
	return str
end


function CreateSheet2JsonStr(sheetName,cmdI,dataStartI,dataEndI)--将表转换为json字符串


	    local types = "["
	    local fields = "["
	    local values = "["
	    local path2 = lfs.currentdir()    --取得当前路径 
		path2=GetPath(path2,"..")

		local filePath=path2 .. '\SubExcel\\'..sheetName..'.xls'
		print(filePath)
	   local  excelFile = excel.WorkBooks:Open(filePath, 0, 0)    --打开EXCEL文件，应使用绝对路


		local st = excelFile.Sheets("DATA")

		local CREATE_X = 1
		while(true)
		do
		  	local v = tostring(st.Cells(CREATE_X, cmdI).Value2)
			if v=="CREATE" then
				break
			end
			CREATE_X=CREATE_X+1
		end
		local fileName = tostring(st.Cells(CREATE_X, cmdI+1).Value2)

		if _G.ISREADJSONFILE then
			local file,er = io.open(jsonPath..fileName..".json","rb")     
			if not file then
				if debugMode then
					print("===================>>>>>string.fromfile failed", filename)
				end
				return nil
			end
			local content = file:read("*a")
			file:close()
			return content,fileName
		end




		local FLDTYPE_X = CREATE_X+1
		while(true)
		do
		  	local v = tostring(st.Cells(FLDTYPE_X, cmdI).Value2)
			if v=="FLDTYPE" then
				break
			end
			FLDTYPE_X=FLDTYPE_X+1
		end



		--生成types字段
		local NullIList = {}
		for i=dataStartI,dataEndI,1 do
			local v = tostring(st.Cells(FLDTYPE_X, i).Value2)
			if(v=="N") then
				NullIList[i]=true
				--table.insert(NullIList, i)
			else
				v="\""..v.."\""
				types=types..v..","
			end
		end
		types=string.sub(types, 1, -2).."]"


	    local FLDNAME_X = FLDTYPE_X+1
		while(true)
		do
		  	local v = tostring(st.Cells(FLDNAME_X, cmdI).Value2)
			if v=="FLDNAME" then
				break
			end
			FLDNAME_X=FLDNAME_X+1
		end


		--生成fields字段
		for i=dataStartI,dataEndI,1 do
			if not NullIList[i] then
				local v = tostring(st.Cells(FLDNAME_X, i).Value2)
				v="\""..v.."\""
				fields=fields..v..","
			end
	
		end
		fields=string.sub(fields, 1, -2).."]"

		--生成values字段
		local Data_X = FLDNAME_X+1
		while(true)
		do
           local t = tostring(st.Cells(Data_X, cmdI).Value2)
           if t=="DATA" then
           		local data = "["
           		for i=dataStartI,dataEndI,1 do
					if not NullIList[i] then
						local v = tostring(st.Cells(Data_X, i).Value2)
						v="\""..v.."\""
						data=data..v..","
					end
			
				end
				data=string.sub(data, 1, -2).."]"

				values=values..data..","

           elseif t=="CLOSE" then
           		break
           end

           Data_X=Data_X+1

		end
	    values=string.sub(values, 1, -2).."]"

		excelFile:Close()

	   local json = "{\"types\":"..types..",\"fields\":"..fields..",\"values\":"..values.."}"
	   return json,fileName
end


function CreateSheet2LuaFlie(sheetName,cmdI,dataStartI,dataEndI,mode,fileName,path)
	local json,file=CreateSheet2JsonStr(sheetName,cmdI,dataStartI,dataEndI)
	local luaTable = json2lua(json,sheetName,mode)
	local luacode = MyLuaToStr(luaTable)

	if isNull(fileName) then
		fileName=file
	end
	if not _G.ISREADJSONFILE then
		os.execute("mkdir "..path)
	end
	local filePath = path..fileName..suffix
	local  f = io.open (filePath,"w+")
	io.output(f)
	io.write(luacode)
	io.close(f)
end

function GetSheetInfo(index)

	local sheetName = tostring(sheet.Cells(index, exportSheetName).Value2)
	local isY = tostring(sheet.Cells(index, exportIsY).Value2)
	local cmdI = tostring(sheet.Cells(index, exportCmd).Value2)
	local dataStartI = tostring(sheet.Cells(index, exportDataStart).Value2)
	local dataEndI = tostring(sheet.Cells(index, exportDataEnd).Value2)
	local subPath = tostring(sheet.Cells(index, exportSubPath).Value2)
	local mode = tostring(sheet.Cells(index, exportMode).Value2)
	local fileName = tostring(sheet.Cells(index, exportFileName).Value2)
	return sheetName,isY,cmdI,dataStartI,dataEndI,subPath,mode,fileName
end


--self:LoadJson("piece","piece",fmtList)
--self:LoadJson("piece","piecebyId")
--self:LoadJson("mission","mission")
--self:LoadJson("effect","effect")

function json2lua(json,filename,fmtList)

	local config = {}

	if fmtList then
		JsonParser.parseFile(json,config, filename , false, fmtList)
	else
		JsonParser.ToHash(json,config, filename , false, "id")
	end 
	return config
end


require("luacom")--引用com插件
require('lfs')    --导入lfs模块用于取得当前路径，和操作EXCEL无关
local JsonParser=require("jsonParser")

suffix=".lua"
local path = lfs.currentdir()    --取得当前路径 
path=GetPath(path,"..")

exportSheetName=1
exportIsY=2
exportCmd=3
exportDataStart=5
exportDataEnd=6
exportSubPath=7
exportMode=8
exportFileName=9
fileRootPath=""

jsonPath = "../Data/json/"

--[[ 创建excel对象 ----------]]
excel = luacom.CreateObject("Excel.Application") --创建新的实例

book = excel.WorkBooks:Open(path .. '\\EggBoost.xls', 0, 0)    --打开EXCEL文件，应使用绝对路

sheet = book.Sheets("Tables")    --使用第一个Sheet，可以用Sheets('SheetName')来指定Sheet

fileRootPath = tostring(sheet.Cells(1, 2).Value2)--x,下，y横

fileRootPath=GetPath(path,fileRootPath)

--local fList = {
	--{"t", "pieces_type"},
	--{"t", "pieces_effect"},
--}
sheetindexStart=3

while (true)
do
	local sheetName,isY,cmdI,dataStartI,dataEndI,subPath,mode,fileName=GetSheetInfo(sheetindexStart)
	if isNull(sheetName) then
		break
	end
	if not isNull(sheetName) and isY=="Y" then
		local filePath =fileRootPath
		if not isNull(subPath) then
			filePath=GetPath(filePath,subPath)
		end
		local flist=nil
		if  not isNull(mode) then
			print(mode)
			flist=loadstring( 'return ' .. mode )()
		end
		print("正在转化:"..sheetName.."...")
		CreateSheet2LuaFlie(sheetName,tonumber(cmdI),tonumber(dataStartI),tonumber(dataEndI),flist,fileName,filePath)
	end

	sheetindexStart=sheetindexStart+1

end


book:Close()
excel.DisplayAlerts = false
excel:Quit()


require("hatch_by_level")